package online.longzipeng.back.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import online.longzipeng.back.pojo.entity.User;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author: lzp
 * @Date: 2021/2/7 15:43
 * 配置将对象生成加密的JSON字符串
 */
public class JWTUtils {

    /**
     * 秘钥
     */
    private static String secret = "lzpisnbandhelikestudyandlikecodehethinkliveistochangethworld";
    /**
     * 过期时间
     */
    private static long expire = 86400L;

    /**
     * 管理端
     * 把指定的 UserDTO 对象 生成 token[jwt]
     */
    public static String generateJwtAdmin(User user) {
        // 加密
        byte[] keyBytes = secret.getBytes();
        // 获得密钥对象
        SecretKey key = Keys.hmacShaKeyFor(keyBytes);
        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expire * 1000))
                .claim("id", user.getId())
                .claim("nickName", user.getNickName())
                .claim("avatarUrl", user.getAvatarUrl())
                .signWith(key, SignatureAlgorithm.HS256).compact();
        return token;
    }


    /**
     * 解析管理端jwt
     *
     * @param jwtToken
     * @return
     */
    public static User checkJwtUserInfo(String jwtToken) {

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret.getBytes()).parseClaimsJws(jwtToken);
        // map
        Claims claims = claimsJws.getBody();
        Long id = claims.get("id", Long.class);
        String nickName = claims.get("nickName", String.class);
        String avatar = claims.get("avatarUrl", String.class);

        return User.builder()
                .id(id)
                .nickName(nickName)
                .avatarUrl(avatar)
                .build();
    }

}
